import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, any> {
  intercept(context: ExecutionContext, next: CallHandler<T>): Observable<any> {
    // 获取 response 对象，这样可以获取到 statusCode （默认成功为 200）
    const response = context.switchToHttp().getResponse();
    const code = response.statusCode;

    return next.handle().pipe(
      map((data) => ({
        code,
        data,
        message: 'Success',
      })),
    );
  }
}
